package postpic.app;

import org.json.JSONObject;

import postpic.app.io.ClientIO;
import postpic.domain.User;
import postpic.domain.action.Action;
import postpic.domain.session.Request;
import postpic.domain.session.Response;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;

public class LoginActivity extends Activity implements OnClickListener {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.login);
	    ImageView headerImage = (ImageView) findViewById(R.id.header_image);
	    ClientIO.connect();
 	}

	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.loginButton:
			//Request r = new Request(Action.LOGIN, null);
			String username   = ((EditText)findViewById(R.id.usernameBox)).getText().toString();
			String password   = ((EditText)findViewById(R.id.passwordBox)).getText().toString();
		
			JSONObject loginObject = new JSONObject();
			loginObject.put("username", username);
			loginObject.put("password", password);

            ClientIO.sendRequest(new Request(Action.LOGIN, loginObject));
			Response response = ClientIO.getResponse();
			
			if (response.isSuccessful()) {
				User user = new User();
				user.populateFromJSON(response.getResponse());
				ClientIO.USER = user;
				Intent myIntent = new Intent(v.getContext(), PostPicActivity.class);
			    v.getContext().startActivity(myIntent);
			} else {
				alertbox("Login Failed");
			    String error = response.getJSON().getString("msg");
			}
			
			break;
			
		case R.id.registerButton:
			Intent myIntent = new Intent(v.getContext(), RegisterActivity.class);
		    v.getContext().startActivity(myIntent);
			break;
			
		default:
			break;
		}
		
	}
	
	public void alertbox(String mymessage)
	   {
	   new AlertDialog.Builder(this)
	      .setMessage(mymessage)
	      .setTitle("")
	      .setCancelable(true)
	      .setNeutralButton("Ok",
	         new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int whichButton){}
	         })
	      .show();
	   }

}
